CanvasRenderingContext2D.prototype.fillTextVertical = function (text, x, y) {
    var context = this;
    var canvas = context.canvas;

    var arrText = text.split('');
    var arrWidth = arrText.map(function (letter) {
        if (letter === 'm') {
            return context.measureText(letter).width - 10;
        } else if (letter === 'H' || letter === 'M' || letter === 'h' || letter === 'g' || letter === 'n' || letter === 'o' || letter === 'p') {
            return context.measureText(letter).width - 3;
        } else if(letter === 'e') {
            return context.measureText(letter).width - 2;
        } else {
            return context.measureText(letter).width + 1;
        }
    });

    var align = context.textAlign;
    var baseline = context.textBaseline;

    if (align === 'left') {
        x = x + Math.max.apply(null, arrWidth) / 2;
    } else if (align === 'right') {
        x = x - Math.max.apply(null, arrWidth) / 2;
    }
    if (baseline === 'bottom' || baseline === 'alphabetic' || baseline === 'ideographic') {
        y = y - arrWidth[0] / 2;
    } else if (baseline === 'top' || baseline === 'hanging') {
        y = y + arrWidth[0] / 2;
    }

    context.textAlign = 'center';
    context.textBaseline = 'middle';

    // 开始逐字绘制
    arrText.forEach(function (letter, index) {
        // 确定下一个字符的纵坐标位置
        var letterWidth = arrWidth[index];
        // 是否需要旋转判断
        var code = letter.charCodeAt(0);
        if (code <= 256) {
            context.translate(x, y);
            // 英文字符，旋转90°
            context.rotate(90 * Math.PI / 180);
            context.translate(-x, -y);
        } else if (index > 0 && text.charCodeAt(index - 1) < 256) {
            // offset fix
            y = y + arrWidth[index - 1] / 2;
        }
        context.fillText(letter, x, y);
        // 旋转坐标系还原成初始态
        context.setTransform(1, 0, 0, 1, 0, 0);

        y = y + letterWidth + 1;
    });
    // 水平垂直对齐方式还原
    context.textAlign = align;
    context.textBaseline = baseline;
};

$("#imgCutConfirm").bind("click",function(){
         $("#containerDiv").hide();
         $("#imgEdit").hide();
         //$("#getCroppedCanvasModal").modal("hide");
    })

    var Width = $(window).width();
    var Height = $(window).height();

    if(Height < 1600){
        $(".qrcode p").css("margin-top","0.5rem");
        // $(".qrcode img").width("15rem");
        // $(".qrcode img").height("15rem");
        $(".upt-btn-row").css("height", "24rem");
        $("#mergePic").css("bottom","3rem");
        $(".swiper-box").css("top", "-8rem");
        $(".tailoring-content").css("height", "80rem");
    }

        var runVideo =  document.getElementById('runVideo');
        var bgm = document.getElementById('audio');
        var randomPic = 1;
        var startBtn = $(".btn-start");
        // setTimeout(function(){
        //     $(".run").css("bottom","50rem");
        // },300)
        setTimeout(function(){
            $(".loading-text").hide();
            startBtn.fadeIn();

                var load = document.getElementById('loadStatus');
                load.addEventListener('click',function () {
                    load.style.display = "none";
                    runVideo.style.display = "block";
                    runVideo.play();
                    $('.swiper-container').show();           
                })

                // document.getElementById('loadStatus').style.display = 'none';
                // $('.swiper-container').show();

                // 初始化swiper
                var mySwiper = new Swiper ('.swiper-container', {
                    direction: 'vertical',
                    speed: 800,
                    on:{
                        init: function(){
                            swiperAnimateCache(this); //隐藏动画元素
                            swiperAnimate(this); //初始化完成开始动画
                        },
                        slideChangeTransitionEnd: function(){
                            swiperAnimate(this); //每个slide切换结束时也运行当前slide动画
                            //this.slides.eq(this.activeIndex).find('.ani').removeClass('ani'); 动画只展现一次，去除ani类名
                        }
                    }
                });
                var btnComLead = document.getElementById('selectComLeader');
                var comLayer = document.getElementById('comLayer');
                var comList = document.querySelectorAll('.com-name');
                var goHc = document.querySelectorAll('.btn-go-hc');
                var allName = [
                    {posit: '皇驰总经理',name:'朱 志 波'},
                    {posit: '马勒(MAHLE)总经理',name:'陈 红 梅'},
                    {posit: '飞利浦售后市场总监',name:'Jamie Hope'},
                    {posit: '德国马牌总经理',name:'戴 立 博'},
                    {posit: '凌度董事长',name:'胥 伟'},
                    {posit: '倍思CMO',name:'罗 豫 润'},
                    {posit: '野马(YEMA)董事长',name:'邱 森 贤'},
                    {posit: '坦克中国区总裁',name:'魏 雷'},
                    {posit: '骑士首席执行官ceo',name:'陈 俊 鸿'},
                    {posit: '骆驼运营总监',name:'刘 渊'},

                    {posit: '爱车屋董事长',name:'李 珩'},
                    {posit: '牧宝Mubo董事长',name:'马 伟'},
                    {posit: '固特异总经理',name:'李 宁'},
                    {posit: '车丽友总经理',name:'厉 忠 臣'},
                    {posit: 'GiGi总经理',name:'廖 勇'},
                    {posit: '北极绒总监',name:'蔡 丽'},
                    {posit: '卡饰社总经理',name:'梁 玉 林'},
                    {posit: '图拉斯运营总监',name:'郑 会 滨'},
                    {posit: '五福金牛董事长',name:'钟 志 强'},
                    {posit: '尼罗河董事长',name:'职 永 涛'},

                    {posit: '途雅总经理',name:'毕 翠 玲'},
                    {posit: '标榜总经理',name:'邹 尚 宏'},
                    {posit: '曼牌中国区售后副总裁',name:'christian.karner'},
                    {posit: '采埃孚中国售后负责人',name:'许 君'},
                    {posit: '欧司朗全国销售经理',name:'张 征'},
                    {posit: '索菲玛亚太区售后总监',name:'张 晶'},
                    {posit: '大师贴膜总经理',name:'刘 凤 喜'},
                    {posit: 'E&U总监',name:'沈 瑛 华'},
                    {posit: '龟牌总监',name:'代 国 林'},
                    {posit: '卡耐总经理',name:'蔡 魁'},

                    {posit: '卡赫总经理',name:'唐 晓 东'},
                    {posit: '龙膜电商经理',name:'沈 仰 锋'},
                    {posit: 'KDX总监',name:'王 一 帆'},
                    {posit: '威固董事长',name:'潘 丽 华'},
                    {posit: '美基总经理',name:'徐 华'},
                    {posit: '圣科总经理',name:'姜 飞 宇'},
                    {posit: '强生电商经理',name:'任 朝 红'},
                    {posit: '维尔卡特品牌总经理',name:'田 雨'},
                    {posit: '亿力事业部总经理',name:'李 一 川'},
                    {posit: '好顺总经理',name:'曲 维 好'},

                    {posit: '乔氏副总经理',name:'吴 静 明'},
                    {posit: '名奢汇运营总监',name:'曾 泽'},
                    {posit: '艾梦露儿总经理',name:'王 会 涛'},
                    {posit: '领臣品牌负责人',name:'杨 超'},
                    {posit: 'ALIS 总经理',name:'郭 正 跃'},
                    {posit: 'Hella海拉总经理',name:'Philippe Thegner'},
                    {posit: '法雷奥总经理',name:'谢 君 山'},
                    {posit: '雪莱特总经理',name:'魏 志 权'},
                    {posit: '灯小亮创始人',name:'刘 亮'},
                    {posit: '捍道CEO',name:'谢 清 泉'}
                ];
                var slogan = [
                    {lt: 'images/chat/l1.png', rt: 'images/chat/r1.png'},
                    {lt: 'images/chat/l2.png', rt: 'images/chat/r2.png'},
                    {lt: 'images/chat/l3.png', rt: 'images/chat/r3.png'},
                    {lt: 'images/chat/l4.png', rt: 'images/chat/r4.png'},
                    {lt: 'images/chat/l5.png', rt: 'images/chat/r5.png'},
                    {lt: 'images/chat/l6.png', rt: 'images/chat/r6.png'},
                    {lt: 'images/chat/l7.png', rt: 'images/chat/r7.png'}
                ];

                // document.getElementById('toUploadSlide').addEventListener('click',function (ev) {
                //     mySwiper.slideTo(2);
                // });
                // 右侧福神大佬
                var dls = [];
                for (var  i = 0; i <= 50; i++) {
                    dls.push('images/dl/'+i+'.png');
                }
                var dlPosit = document.getElementById('dlPosit');
                var dlName = document.getElementById('dlName');
                dlPosit.innerText = allName[0].posit;
                dlName.innerText = allName[0].name;
                handleTitle(1);
                function randomSlogan() {
                    var randomSlog = parseInt(Math.random()*7);
                    console.log(randomSlog);
                    var chatLt = document.getElementById('chatLt');
                    var chatRt = document.getElementById('chatRt');
                    chatLt.src = slogan[randomSlog].lt;
                    chatRt.src = slogan[randomSlog].rt;
                }
                // 修改不同大佬的名牌及相应背景
                function handleTitle(id) {
                    var dlPosit = document.getElementById('dlPosit');
                    var dlName = document.getElementById('dlName');
                    //获取设备宽度
                    var  clientWidth = document.documentElement.clientWidth;
                    var fontWidth = clientWidth * 23 / 750;

                    var dlFx = document.getElementById('perDl');
                    dlFx.style.background = "url("+dls[id]+") no-repeat center top";
                    dlFx.style.backgroundSize = '100% 57.7rem';

                    var positCanvas = document.createElement('canvas');
                    positCanvas.id = "textCanvas";
                    positCanvas.width = 38;
                    positCanvas.height = 400;
                    $('#dlPosit').html('').append(positCanvas);
                    var poContext = positCanvas.getContext('2d');
                    poContext.font = 'bold '+fontWidth+'px "Microsoft Yahei", sans-serif';
                    poContext.fillStyle = '#b76848';
                    poContext.textAlign = 'center';
                    poContext.textBaseline = 'middle';
                    var drawPositY = (400 - poContext.measureText(allName[id-1].posit).width) / 2;

                    poContext.fillTextVertical(allName[id-1].posit, positCanvas.width / 2, drawPositY);

                    // dlPosit.innerText = allName[id-1].posit;
                    $('.can-name').css('display', 'none');
                    $('#textCanvas').css('display','block');
                    var canvas = document.createElement('canvas');
                    canvas.id = "textCanvas";
                    canvas.width = 38;
                    canvas.height = 400;
                    $('#dlName').html('').append(canvas);
                    var context = canvas.getContext('2d');
                    // canvas.height = context.measureText(text).width;
                    context.font = 'bold '+fontWidth+'px "Microsoft Yahei", sans-serif';
                    context.fillStyle = '#b76848';
                    context.textAlign = 'center';
                    context.textBaseline = 'middle';
                    var drawY = (400 - context.measureText(allName[id-1].name).width) / 2;
                    context.fillTextVertical(allName[id-1].name, canvas.width / 2, drawY);

                }
                btnComLead.addEventListener('click',function (e) {
                    document.querySelector('.btn-ch-dl').classList.add('active');
                    comLayer.style.display = 'block';
                });
                for (var i = 0; i < comList.length; i++) {
                    comList[i].addEventListener("click", function (e) {
                        var comId = this.getAttribute('data-id');
                        handleTitle(comId);
                        randomSlogan();
                        /*comLayer.classList.remove('zoomIn');
                        comLayer.classList.add('zoomOut');
                        comLayer.setAttribute('swiper-animate-effect', 'zoomOut');*/
                        comLayer.style.display = 'none';
                        // return e.preventDefault();
                    });
                }
                for (var i = 0; i < goHc.length; i++) {
                    goHc[i].addEventListener('click', function () {
                        mySwiper.slideTo(1);
                        bgm.play();
                    })
                }


                //视频播放完毕
                runVideo.addEventListener('ended', function () {
                    console.log("end")
                    //TestCanvas.style.display = 'none';
                    runVideo.style.opacity = 0;
                    bgm.play();
                    document.getElementById('videoEnd').style.display = 'block';
                });

                // 随机选择新年福星
                document.getElementById('selectFx').addEventListener('click',function (ev) {
                    var changePic = document.getElementById('perUser');
                    randomPic = parseInt(Math.random()*3) + 1;
                    c.style.display = "none";
                    switch (randomPic) {
                        case 1:
                            changePic.style.background = 'url("images/bg_fs1s.png") no-repeat center center';
                            changePic.style.backgroundSize = '100% 100%';
                            maleBg.src = "images/bg_fs1s.png";
                            sanm();
                            break;
                        case 2:
                            changePic.style.background = 'url("images/bg_fs2s.png") no-repeat center center';
                            changePic.style.backgroundSize = '100% 100%';
                            maleBg.src = "images/bg_fs2s.png";
                            sanm();
                            break;
                        case 3:
                            changePic.style.background = 'url("images/bg_fs3s.png") no-repeat center center';
                            changePic.style.backgroundSize = '100% 100%';
                            maleBg.src = "images/bg_fs3s.png";
                            sanm();
                            break;
                        default:
                            changePic.style.background = 'url("images/bg_fs1s.png") no-repeat center center';
                            changePic.style.backgroundSize = '100% 100%';
                            maleBg.src = "images/bg_fs1s.png";
                            sanm();
                    }
                });

                // $('#uploadUserPic').click(function (ev) {
                //     $('#upload_file').trigger('click');
                // });

                document.getElementById('mergePic').addEventListener('click',function (ev) {
                    $('.save-hide').hide();
                    document.querySelector('.qrcode').style.display = 'block';
                    var canvas2 = document.createElement("canvas");
                    var _canvas = document.querySelector('#testImg');
                    var w = parseInt(window.getComputedStyle(_canvas).width);
                    var h = parseInt(window.getComputedStyle(_canvas).height);
                    // 将canvas画布放大若干倍，解决模糊
                    canvas2.width = w * 1;
                    canvas2.height = h * 1;
                    canvas2.style.width = w + "px";
                    canvas2.style.height = h + "px";
                    // 对context的参数修改,translate-偏移量
                    //  var context = canvas.getContext("2d");
                    //  context.translate(0,0);
                    var context = canvas2.getContext("2d");
                    context.scale(1, 1);
                    console.log(w)
                    console.log(h)
                    html2canvas(document.querySelector('#testImg'), { canvas: canvas2,
                        scale: 1,
                        width: w,
                        height: h
                    }).then(function(canvas) {
                        var url = canvas.toDataURL();
                        document.getElementById("sanImg").src = url;
                        // document.querySelector('.slide4').appendChild(canvas);
                        // //canvas转换成url，然后利用a标签的download属性，直接下载
                        // document.querySelector(".down").setAttribute('href', canvas.toDataURL());
                        mySwiper.slideTo(2)
                    });
                });

        }, 2000)

var main = document.getElementById('main');
var img = document.getElementById('img');
var c = document.getElementById("myCanvas");
c.width = 500;
var ctx = c.getContext("2d");

//合成
var theFace;
var faceImg = document.getElementById('theFace');
var faceC = document.getElementById('faceCtx');
var faceCtx = faceC.getContext('2d');
var maleBg = document.getElementById('maleBg');
// 识别参数
var stepSize = 1;
var initialScale = 2;

//初始化识别任务
var faceLeft = 0;
var faceTop = 0;
var prop = 1;

//图像上传
function selectImg(file) {
    $(".tailoring-container").show();
    if (!file.files || !file.files[0]){
        return;
    }
    var reader = new FileReader();
    reader.onload = function (evt) {
        var replaceSrc = evt.target.result;
        //更换cropper的图片
        $('#tailoringImg').cropper('replace', replaceSrc,false);//默认false，适应高度，不失真
        
    }
    reader.readAsDataURL(file.files[0]);
}

//cropper图片裁剪
$('#tailoringImg').cropper({
    aspectRatio: 1/1.2,//默认比例
    preview: '.previewImg',//预览视图
    dragMode: 'move',
    guides: false,  //裁剪框的虚线(九宫格)
    autoCropArea: 0.5,  //0-1之间的数值，定义自动剪裁区域的大小，默认0.8
    movable: true, //是否允许移动图片
    dragCrop: false,  //是否允许移除当前的剪裁框，并通过拖动来新建一个剪裁框区域
    cropBoxMovable: false,  //是否允许移动剪裁框
    cropBoxResizable: false,
    resizable: false,  //是否允许改变裁剪框的大小
    zoomable: true,  //是否允许缩放图片大小
    mouseWheelZoom: true,  //是否允许通过鼠标滚轮来缩放图片
    touchDragZoom: true,  //是否允许通过触摸移动来缩放图片
    rotatable: true,  //是否允许旋转图片
    crop: function(e) {
        // 输出结果数据裁剪图像。
    }
});

//旋转
$(".cropper-rotate-btn").on("click",function () {
    $('#tailoringImg').cropper("rotate", 15);
});
//复位
$(".cropper-reset-btn").on("click",function () {
    $('#tailoringImg').cropper("reset");
});
//换向
var flagX = true;
$(".cropper-scaleX-btn").on("click",function () {
    if(flagX){
        $('#tailoringImg').cropper("scaleX", -1);
        flagX = false;
    }else{
        $('#tailoringImg').cropper("scaleX", 1);
        flagX = true;
    }
    flagX != flagX;
});

var base64url = '';
var newFace = document.getElementById('theFace');
//裁剪后的处理
$("#sureCut").on("click",function () {
    // if ($("#tailoringImg").attr("src") == null ){
    //     return false;
    // }else{
        //.cropper('setCropBoxData',{width:200,height:100});
        //$('#tailoringImg').cropper('setCropBoxData',{width:126,height:175});
        var cas = $('#tailoringImg').cropper('getCroppedCanvas');//获取被裁剪后的canvas
        base64url = cas.toDataURL('image/png'); //转换为base64地址形式
        newFace.src = base64url;//显示为图片的形式
        setTimeout(function(){
            sanm();
            //关闭裁剪框
            closeTailor();
        },200);
        $('#perUser').css('display', 'none');
    // }
});
//关闭裁剪框
function closeTailor() {
    $(".tailoring-container").hide();
    $('.btn-merge').addClass('active');
}

function sanm(){
    $("#uploadUserPic").val("");
    c.width = 380;
    c.height = 683;
    ctx.clearRect(0, 0, c.width, c.height);
    faceImg.src = base64url;
    faceImg.width = 117;
    faceImg.height = 163;
    var self = faceImg;
    setTimeout(function(){
        AlloyImage(self).act("灰度处理").add(
            AlloyImage(self.width, self.height, "#E1B9A3")
            .act("高斯模糊", 10)
            .act("色相/饱和度调节", 10, 15, 0, true)
            ,
            "叠加"
        ).replace(self);
        setTimeout(function() {
            if(randomPic==3){
                ctx.drawImage(newFace, 0, 0, 117, 163, 133, 65, 117, 163);
            }
            else{
                ctx.drawImage(newFace, 0, 0, 117, 163, 133, 65, 117, 163);
            }
            ctx.drawImage(maleBg, 0, 0);
            c.style.display = "block";
            newFace.src = "";
        }, 400);
    }, 300)
    // faceImg.onload = function() {

    // };
}